package com.financing.platform.service.impl;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.Notification;
import cn.jpush.api.report.ReceivedsResult;
import com.financing.platform.SMSDict;
import com.financing.platform.dto.PhonePushDTO;
import com.financing.platform.service.IJPushService;
import com.financing.platform.util.Dict;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author qiye
 *
 */
@Service("jPushService")
public class JPushServiceImpl extends BaseServiceImpl implements IJPushService {
	
	private Logger log = Logger.getLogger(this.getClass());
	
	@Value("#{settings['JGmasterSecret']}")
	private String masterSecret;
	
	@Value("#{settings['JGappKey']}")
	private String appKey;
	
	@Value("#{settings['JGmasterSecretShop']}")
	private String masterSecretShop;
	
	@Value("#{settings['JGappKeyShop']}")
	private String appKeyShop;
	
	

	@Value("#{settings['JGuangIosFlag']}")
	private  Boolean iosFlag;

	@Override
	public Map<String,Object> pushAllPhone(PhonePushDTO dto) throws Exception {
		
		Map<String,Object> result = new HashMap<String,Object>();
		JPushClient jpushClient;
		
		if(!StringUtils.isBlank(dto.getJpushSource()) && dto.getJpushSource().equals("shop")){
			jpushClient = new JPushClient(masterSecretShop, appKeyShop, 3);	
		}else{
			jpushClient = new JPushClient(masterSecret, appKey, 3);
		}

		//判断 是否-iosFlag
		log.info("buildPushObject_ios_alertWithTitle  iosFlag:"+iosFlag);
        // For push, all you need do is to build PushPayload object.
        PushPayload payloadAndroid = buildPushObject_android_alertWithTitle(dto.getContent(),dto.getTitle(),dto.getExtraMap(),dto.getAliseList());
        PushPayload payloadIos = buildPushObject_ios_alertWithTitle(dto.getContent(),dto.getTitle(),dto.getExtraMap(),dto.getAliseList(),iosFlag);
        try {
        	//如果aliseList不为空则为定点推送，如果alise 在android中推送失败，尝试ios推送。aliseList为空则先android推送全部，再ios推送全部
        	if(null != dto.getAliseList() && dto.getAliseList().size()>0){
//        		OnlineStatus onlineStatus = jpushClient.getUserOnlineStatus(dto.getAliseList().get(0)).get(dto.getAliseList().get(0));
        		//设备在线则推送  免费版无法获取设备状态，付费版才能用
//        		if(onlineStatus.getOnline()){
        			result.put("isOnline", true);
	        		try{
	            			PushResult resultAndroid = jpushClient.sendPush(payloadAndroid);
	            			log.info("Got result  - resultAndroid" + resultAndroid);
	            			 result.put("msg_id", resultAndroid.msg_id);
	            			 result.put("sendNo", resultAndroid.sendno);
	            		}catch(Exception e){
	            			PushResult resultIos = jpushClient.sendPush(payloadIos);
	            			 log.info("Got result  resultIos- " + resultIos);
	            			 result.put("msg_id", resultIos.msg_id);
	            			 result.put("sendNo", resultIos.sendno);
	            		}
	        		
//        		}else{
//        			result.put("isOnline", false);
//        			 return result;
//        		}
        		
        	}else{
        		// 测试环境 ios和android需要不同账号测试
        		PushResult resultAndroid = jpushClient.sendPush(payloadAndroid);
        		log.info("Got result  - resultAndroid" + resultAndroid);
        		
                PushResult resultIos = jpushClient.sendPush(payloadIos);
                log.info("Got result  resultIos- " + resultIos);
                result.put("msg_id", resultAndroid.msg_id+","+resultIos.msg_id);
                result.put("sendNo", resultAndroid.sendno+","+resultIos.sendno);
        		
        	}
            
            
           result.put(SMSDict.result, Dict.sms_send_success);
          
        } catch (APIConnectionException e) {
            // Connection error, should retry later
        	log.error("Connection error, should retry later", e);
        	result.put(SMSDict.result, Dict.sms_send_fail);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
        	log.error("Should review the error, and fix the request", e);
        	log.info("HTTP Status: " + e.getStatus());
        	log.info("Error Code: " + e.getErrorCode());
        	log.info("Error Message: " + e.getErrorMessage());
        	result.put(SMSDict.result, Dict.sms_send_fail);
        }		
        
        return result;
	}
	
	 /**
	  * 推送android通知
	  * @param alert
	  * @param extraMap
	  * @param aliasesList
	  * @return
	  */
	 public static PushPayload buildPushObject_android_alertWithTitle(String alert,String title,Map<String,String> extraMap,List<String> aliasesList) {
		 cn.jpush.api.push.model.PushPayload.Builder builder = PushPayload.newBuilder().setPlatform(Platform.android());
		 
		 if(aliasesList != null && !aliasesList.isEmpty()){
			 builder.setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.registrationId(aliasesList))
                        .build());
		 }else{
			 builder.setAudience(Audience.all());
		 }
		 builder.setNotification(Notification.android(alert, title, extraMap));
		 return builder.build();
	    }
	 /**
	  * 推送ios通知
	  * @param alert
	  * @param extraMap
	  * @param aliasesList
	  * @return
	  */
	 public static PushPayload buildPushObject_ios_alertWithTitle(String alert,String title,Map<String,String> extraMap,List<String> aliasesList,Boolean iosFlag) {
		 cn.jpush.api.push.model.PushPayload.Builder builder = PushPayload.newBuilder().setPlatform(Platform.ios());


		 if(aliasesList != null && !aliasesList.isEmpty()){
			 builder.setAudience(Audience.newBuilder()
					 .addAudienceTarget(AudienceTarget.registrationId(aliasesList))
                     .build());
		 }else{
			 builder.setAudience(Audience.all());
		 }
		 
		 builder.setNotification( Notification.ios_auto_badge().ios(alert, extraMap));
		 builder.setOptions(Options.newBuilder()
                .setApnsProduction(iosFlag==null?true:iosFlag)
                .build());
		 return builder.build();
	    }
	 
	 /**
	  * 推送消息
	  * @param alert
	  * @param extraMap
	  * @param aliasesList
	  * @return
	  */
	 public static PushPayload buildPushObject_messageWithTitle(String alert,String title,Map<String,String> extraMap,List<String> aliasesList) {
		 cn.jpush.api.push.model.PushPayload.Builder builder = PushPayload.newBuilder().setPlatform(Platform.android());
		 
		 if(aliasesList != null && !aliasesList.isEmpty()){
			 builder.setAudience(Audience.alias(aliasesList));
		 }else{
			 builder.setAudience(Audience.all());
		 }
		 if(extraMap != null && !extraMap.isEmpty()){
			 builder.setMessage(Message.newBuilder()
                     .setMsgContent(alert)
                     .addExtras(extraMap)
                     .setTitle(title)
                     .build());
		 }else{
			 builder.setMessage(Message.newBuilder()
                     .setMsgContent(alert)
                     .addExtras(extraMap)
                     .setTitle(title)
                     .build());
		 }
		 builder.setNotification(Notification.ios_auto_badge());
		 return builder.build();
	    }
	 /**
	   * 获取统计样例
	   * @return
	   */
	  private ReceivedsResult getReport(String msgIds){
		  JPushClient jpushClient = new JPushClient(masterSecret, appKey);
		  ReceivedsResult result = null;
	        try {
	             result = jpushClient.getReportReceiveds(msgIds);
	            log.info("Got result - " + result);

	        } catch (APIConnectionException e) {
	            // Connection error, should retry later
	        	log.error("Connection error, should retry later", e);

	        } catch (APIRequestException e) {
	            // Should review the error, and fix the request
	        	log.error("Should review the error, and fix the request", e);
	        	log.info("HTTP Status: " + e.getStatus());
	        	log.info("Error Code: " + e.getErrorCode());
	        	log.info("Error Message: " + e.getErrorMessage());
	        }
	        return result;
	  }
}

	
